package com.waves.netty;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;

import java.io.IOException;
import java.net.InetSocketAddress;

/**
 * 客户端
 */
public class HelloClient {
    public static void main(String[] args) throws InterruptedException, IOException {
        // 1.创建客户端启动类
        ChannelFuture client = new Bootstrap()
                // 2.创建处理器组 包含线程池和Selector，用于实现并发和监听就绪通道
                .group(new NioEventLoopGroup())
                // 3.选择通道的实现，可以是NIO或BIO
                .channel(NioSocketChannel.class)
                // 4.添加处理器
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    // 5. 具体初始化
                    @Override
                    protected void initChannel(NioSocketChannel ch) {
                        ch.pipeline().addLast(new StringEncoder());
                    }
                })
                // 5.进行连接
                .connect(new InetSocketAddress("localhost", 8080))
                // 6.等待连接建立完毕
                .sync();
        // 发送数据
        Channel channel = client.channel();
        channel.writeAndFlush("hello world");
        System.in.read();
    }
}
